import { RouteRecordRaw } from 'vue-router'
import { IBreadItem } from '@/base-ui/breadcrumb/types'

let firstMenu: any

// 根据后端路由遍历本地路由，过滤生成权限路由
export function mapMenusToRoutes(roleMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []

  // 加载所有的文件，配置对应的route
  const allRoutes: RouteRecordRaw[] = []
  const routeFiles = require.context('../router/main', true, /\.ts/)

  routeFiles.keys().forEach(item => {
    const route = require('../router/main' + item.split('.')[1])
    allRoutes.push(route.default)
  })
  console.log('allRoutes',allRoutes)
  
  // 根据菜单返回相应的 route
  const userRoute = (menus: any[]) => {
    for(const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find(item => item.path === menu.url)
        if (route) {
          routes.push(route)
          if (!firstMenu) {
            firstMenu = route
          }
        }
      } else {
        userRoute(menu.children)
      }
    }
  }

  userRoute(roleMenus)

  return routes
}

// 遍历路由，获取所有按钮权限
export function mapMenusToBtnPermission(roleMenus: any[]) {
  const permissions: string[] = []

  console.log('roleMenus', roleMenus)

  const reducePermission = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type == 1 || menu.type == 2) {
        reducePermission(menu.children || [])
      } else if (menu.type == 3) {
        permissions.push(menu.permission)
      }
    }
  }

  reducePermission(roleMenus)

  // console.log(permissions)

  return permissions
}

// 面包屑
export function pathMapBreakcrumbs(userMenus: any[], path: string) {
  const breadCrumb: IBreadItem[] = []

  pathMapToMenus(userMenus, path, breadCrumb)
  return breadCrumb
}

// /main/system/role  -> type === 2 对应menu
// 页面刷新，拿到刷新的menu
export function pathMapToMenus(
  userMenus: any[],
  path: string,
  breadCrumb?: IBreadItem[]): any {
  for(const menu of userMenus) {
    if (menu.type === 1 ) {
      const findPath = pathMapToMenus(menu.children ?? [], path)
      if (findPath) {
        if (breadCrumb) {
          breadCrumb?.push({ name: menu.name })
          breadCrumb?.push({ name: findPath.name })
        }
        return findPath
      }
    } else if (menu.type === 2 && menu.url === path) {
      return menu
    }
  }
}

// 遍历数，找到所有子节点id
export function menuToTreeKeys(menuList: any[]) {
  const menu: number[] = []

  const reduceTree = (menuList: any[]) => {
    for(let item of menuList) {
      if (item.children) {
        reduceTree(item.children)
      } else {
        menu.push(item.id)
      }
    }
  }

  reduceTree(menuList)

  return menu
}

export { firstMenu }